﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLayer.Model.Repositories.Abstract;
using BusinessLayer.Model.Services.Abstract;
using BusinessLayer.Model.Services.Concrete;
using BusinessLayer.Model.Entities;
using DataAccess.Repositories;
using DataAccess.Services;

namespace intecnologia.Admin
{
    public partial class Pictures : System.Web.UI.Page
    {
        protected IGalleryService _galleryService = new GalleryService();
        private IPictureRepository _pictureRepository = new PictureRepository();
        private ISessionService _sessionService = new SessionService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (_sessionService.SessionExpired())
                Response.Redirect("~/Admin/Default.aspx");

            if (!IsPostBack)
                LoadPictures();
        }

        protected int PicturesCount()
        {
            return _pictureRepository.FetchAll().Count();
        }

        protected void picturesDataList_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "DeleteImage")
                DeleteImg(source, e);
        }

        protected void btnAddPictures_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/UploadPictures.aspx");
        }

        private void LoadPictures()
        {
            picturesDataList.DataSource = _pictureRepository.FetchAll();
            picturesDataList.DataBind();
        }

        private void DeleteImg(object source, DataListCommandEventArgs e)
        {
            DataList dl = (DataList)picturesDataList;
            Guid picID = new Guid(dl.DataKeys[e.Item.ItemIndex].ToString());

            _galleryService.DeletePicture(_pictureRepository.FetchByID(picID));
            _pictureRepository.Remove(_pictureRepository.FetchByID(picID));
            _pictureRepository.SubmitChanges();

            LoadPictures();
        }
    }
}
